package com.zz.yt.lib.ui.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.delegate.BaseDelegate;
import com.whf.android.jar.util.callback.CallbackManager;
import com.whf.android.jar.util.callback.CallbackType;
import com.whf.android.jar.util.callback.IGlobalCallback;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.document.util.AnnexUtil;
import com.zz.yt.lib.ui.callback.RequestCodes;
import com.zz.yt.lib.ui.delegate.scanner.ScannerDelegate;
import com.zz.yt.lib.ui.delegate.signature.added.SignatureAddedDelegate;
import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.zz.yt.lib.ui.delegate.web.WebUiDelegate;
import com.zz.yt.lib.ui.listener.OnClickObjectListener;
import com.zz.yt.lib.ui.listener.OnClickStringListener;
import com.zz.yt.lib.ui.popup.view.TipsPopup;
import com.zz.yt.lib.ui.privacy.IPrivacyListener;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/***
 * 动态权限注入
 * @author qf
 * @version 1.0
 */
@RuntimePermissions
public abstract class PerCheckerDelegate extends BaseDelegate {

    /**
     * 设置跳转到用户协议和隐私政策
     */
    protected IPrivacyListener mIPrivacyListener = null;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof IPrivacyListener) {
            mIPrivacyListener = (IPrivacyListener) context;
        }
    }

    //(选择文件)不是直接调用方法
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startFile(OnClickObjectListener listener) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                ActivityUtils.startActivityForResult(Latte.getActivity(), intent, RequestCodes.REFRESH);
                return;
            }
        }
        if (listener != null) {
            listener.onClick("文件写入权限");
        }
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileDenied() {
        ToastUtils.showLong("不允许存储文件");
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileNever() {
        ToastUtils.showLong("永久拒绝存储文件权限");
    }

    /**
     * @param listener：文件写入权限
     */
    public void startFileWithCheck(OnClickObjectListener listener) {
        PerCheckerDelegatePermissionsDispatcher.startFileWithPermissionCheck(this, listener);
    }

    /**
     * @param delegate：选择文件
     */
    public void startFilePickerWithCheck(final BaseDelegate delegate) {
        startFileWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                AnnexUtil.Bundle()
                        .setContent(delegate)
                        .onAddAnnexClickListener();
            }
        });
    }

    /**
     * @param delegate：电子签名
     */
    public void startSignatureWithCheck(final BaseDelegate delegate) {
        startFileWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                delegate.getSupportDelegate().startForResult(SignatureAddedDelegate.create(),
                                RequestCodes.SIGNATURE);
            }
        });
    }

    /**
     * 跳转到电子签名签字界面
     */
    protected void startSignatureDelegate() {
        startSignatureDelegate(null);
    }

    /**
     * @param signature：电子签名签字地址
     */
    protected void startSignatureDelegate(final String signature) {
        startFileWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                startForResult(SignatureAddedDelegate.create(signature), RequestCodes.SIGNATURE);
            }
        });
    }

    /*********************************** CAMERA 拍照权限（二维码）**************************************/

    //拍照权限(不直接调用)
    @NeedsPermission(Manifest.permission.CAMERA)
    void startCamera(OnClickObjectListener listener) {
        if (listener != null) {
            listener.onClick("拍照权限");
        }
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onCameraDenied() {
        ToastUtils.showLong("不允许拍照");
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onCameraNever() {
        ToastUtils.showLong("永久拒绝拍照权限");
    }

    /**
     * @param listener：拍照权限
     */
    public void startCameraWithCheck(OnClickObjectListener listener) {
        PerCheckerDelegatePermissionsDispatcher.startCameraWithPermissionCheck(this, listener);
    }

    /**
     * @param delegate：扫描二维码
     */
    public void startScanWithCheck(final BaseDelegate delegate) {
        startCameraWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                delegate.getSupportDelegate().startForResult(new ScannerDelegate(), RequestCodes.SCAN);
            }
        });
    }

    /**
     * 扫描二维码
     */
    public void startScanWithCheck() {
        startCameraWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                ActivityUtils.startActivityForResult(Latte.getActivity(), intent, RequestCodes.SCAN);
            }
        });
    }

    /***************************************** LOCATION 定位权限***************************************/

    //定位权限(不直接调用)
    @NeedsPermission({
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION})
    void startClick(OnClickObjectListener listener, boolean isNeedBack) {
        //是Android 9及以上的。并且需要申请后台权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isNeedBack) {
            //先申请前台定位权限，再申请后台单位权限
            PerCheckerDelegatePermissionsDispatcher.startClickQbgWithPermissionCheck(this, listener);
        } else {
            if (listener != null) {
                listener.onClick(null);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @NeedsPermission({Manifest.permission.ACCESS_BACKGROUND_LOCATION})
    void startClickQbg(OnClickObjectListener listener) {
        if (listener != null) {
            listener.onClick(null);
        }
    }

    /**
     * @param listener：定位权限
     */
    public void starClickWithCheck(OnClickObjectListener listener) {
        //默认不开启后台单位权限
        PerCheckerDelegatePermissionsDispatcher.startClickWithPermissionCheck(this,
                listener, false);
    }

    /**
     * @param listener：定位权限
     */
    public void starClickWithCheck(OnClickObjectListener listener, boolean isNeedBack) {
        PerCheckerDelegatePermissionsDispatcher.startClickWithPermissionCheck(this,
                listener, isNeedBack);
    }

    /**
     * @param delegate：定位
     */
    public void startLocationWithCheck(final BaseDelegate delegate, final BaseDelegate delegateLocation) {
        starClickWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                delegate.getSupportDelegate().startForResult(delegateLocation, RequestCodes.LOCATION);
            }
        });
    }

    /**
     * @param delegate：定位
     */
    public void startLocationWithCheck(final BaseDelegate delegate, final Class<? extends Activity> clz) {
        starClickWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                ActivityUtils.startActivityForResult(delegate, clz, RequestCodes.LOCATION);
            }
        });
    }

    @OnPermissionDenied({
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION})
    void onLocationDenied() {
        ToastUtils.showLong("不允许定位");
    }

    @OnNeverAskAgain({
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION})
    void onLocationNever() {
        ToastUtils.showLong("永久拒绝定位权限");
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @OnPermissionDenied(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    void onLocationBgDenied() {
        ToastUtils.showLong("不允许后台定位");
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @OnNeverAskAgain(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    void onLocationBgNever() {
        ToastUtils.showLong("永久拒绝后台定位权限");
    }

    /************************************* 安装未知来源权限 *****************************************/

    private final int INSTALL_APP_SOURCES_CODE = 1256;

    /*** 8.0以上系统设置危险权限（安装未知来源权限）*/
    protected void setInstallPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先判断是否有安装未知来源应用的权限
            boolean haveInstallPermission = _mActivity.getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                installApk();
            } else {
                show();
            }
        } else {
            installApk();
        }
    }

    protected void installApk() {
        LatteLogger.i("成功获取安装权限");
    }

    /*** 是否允许更新应用 */
    private void show() {
        TipsPopup.create()
                .setTitle("是否允许更新应用？")
                .setDate("设备和个人信息数据容易受到未知来源应用的攻击，点击“允许”表示您同意承担由此带来的风险。")
                .setText("允许")
                .setOnClickListener(new OnClickDecisionListener() {
                    @Override
                    public void onConfirm(Object decision) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            startInstallPermissionSettingActivity();
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                })
                .popup();
    }

    /*** 开启安装未知来源权限 */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri parse = Uri.parse("package:" + Latte.getActivity().getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, parse);
        ActivityUtils.startActivityForResult(Latte.getActivity(), intent, INSTALL_APP_SOURCES_CODE);
    }

    /******************************************* 权限回调 ******************************************/

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PerCheckerDelegatePermissionsDispatcher.onRequestPermissionsResult(this,
                requestCode, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == INSTALL_APP_SOURCES_CODE) {
            //成功获取安装权限
            installApk();
        }
    }


    //******************************************  处理二维码扫描结果  ***************************/

    /**
     * 处理二维码扫描结果
     */
    protected void setScanResult(int requestCode, @Nullable Intent data, OnClickStringListener listener) {
        if (requestCode == RequestCodes.SCAN) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (listener != null) {
                        listener.onClick(result);
                    } else {
                        @SuppressWarnings("unchecked") final IGlobalCallback<String> callback = CallbackManager
                                .getInstance()
                                .getCallback(CallbackType.ON_SCAN);
                        if (callback != null) {
                            callback.executeCallback(result);
                        }
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtils.showShort("解析二维码失败");
                }
            }
        }
    }

    //******************************************* 附件回调 ******************************************/


    /**
     * @param delegate：跳转,返回可以刷新界面
     */
    protected void startForResult(BaseDelegate delegate) {
        startForResult(delegate, RequestCodes.REFRESH);
    }

    /**
     * @param title：跳转网页,显示的标题
     * @param url：跳转网页,显示的内容
     */
    protected final void startWebUi(String title, String url) {
        start(WebUiDelegate.create(title, url));
    }

    /**
     * @param title：跳转网页,显示的标题
     * @param url：跳转网页,显示的内容
     */
    protected final void startForResultWebUi(String title, String url) {
        startForResult(WebUiDelegate.create(title, url));
    }

}
